<template>
  <div id="wechatUser" class="app-container">
    <!--搜索条件-->
    <div class="filter-container">
      <el-form :model="listQuery" :inline="true">
        <el-form-item>
          <application-key-select v-model="listQuery.appId" :type="listQuery.type" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="listQuery.tagIdList" placeholder="用户标签" style="width:100%">
            <el-option :label="'全部('+total+')'" value="" />
            <el-option
              v-for="item in tagOptions"
              :key="item.id"
              :label="item.tagName+'('+item.count+')'"
              :value="item.tagId*1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="listQuery.keyword" placeholder="请输入昵称" style="width: 140px;" class="filter-item" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item>
          <el-button plain class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
          <el-button plain class="filter-item" icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container flex-main">
      <div class="table-container-header">
        <table-toolbar :create="false" @remove="removeRecord" @refresh="handleFilter">
          <template>
            <el-button icon="el-icon-sort" @click="handleSynchronizationUser">同步粉丝</el-button>
          </template>
          <template slot="rightTool">
            <export-drop-down class-name="wechatUser" :list-query="listQuery" title="微信粉丝" />
          </template>
        </table-toolbar>
      </div>
      <!-- 列表 -->
      <el-table
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        height="100%"
        highlight-current-row
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="sortChange">
        <el-table-column type="selection" width="60" />
        <el-table-column align="center" prop="id" label="序号" width="60">
          <template slot-scope="scope">{{ scope.$index+1 }}</template>
        </el-table-column>
        <el-table-column label="头像" prop="headImageUrl" width="70" align="center">
          <template slot-scope="scope">
            <img :src="scope.row.headImageUrl" class="common-round-image-32" :title="scope.row.nickName" @error="handleImageError">
          </template>
        </el-table-column>
        <el-table-column label="用户标识" width="240" prop="openId" align="center">
          <template slot-scope="scope">
            <span class="color-primary common-cursor" @click="handleLook(scope.row)">{{ scope.row.openId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="关注渠道" width="220" prop="subscribeScene" align="center">
          <template slot-scope="scope">
            {{ (subscribeScenes.filter((item)=>item.name===scope.row.subscribeScene)[0]).label }}
          </template>
        </el-table-column>
        <el-table-column label="用户昵称" min-width="200" :show-overflow-tooltip="true" prop="nickName" align="center" />
        <el-table-column label="性别" prop="sex" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.sex==1?"男":"女" }}</template>
        </el-table-column>
        <el-table-column align="center" label="关注时间" width="160">
          <template slot-scope="scope">{{ (scope.row.subscripeTime*1000 ) | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
        </el-table-column>
        <el-table-column align="center" label="状态" width="160">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isCancle==0" type="success">已关注</el-tag>
            <el-tag v-if="scope.row.isCancle==1" type="danger">已取消</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="gmtCreated" sortable label="取消时间" width="160">
          <template slot-scope="scope">
            <span v-if="scope.row.isCancle==1">{{ scope.row.unSubscripeTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="语言" width="100" prop="language" align="center" />
        <el-table-column :show-overflow-tooltip="true" label="所属地区" prop="sex" min-width="300" align="center">
          <template slot-scope="scope">{{ scope.row.country }}-{{ scope.row.province }}-{{ scope.row.city }}</template>
        </el-table-column>

        <el-table-column label="操作" align="center" fixed="right" width="90">
          <template slot-scope="scope">
            <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
            <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination_handler">
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
      </div>
    </div>
    <model-dialog
      title="查看"
      :visible.sync="dialogVisible"
      width="700px"
      :show-close="false"
      @close="dialogVisible=!dialogVisible">
      <div class="wechatUserDetails">
        <el-row class="item" :gutter="10">
          <el-col :span="20">
            <el-row class="item" :gutter="10">
              <el-col :span="14">
                主键：{{ wechatUserRecord.id }}
              </el-col>
              <el-col :span="10">
                AppId：{{ wechatUserRecord.appId }}
              </el-col>
            </el-row>
            <el-row class="item" :gutter="10">
              <el-col :span="14">
                用户标识：{{ wechatUserRecord.openId }}
              </el-col>
              <el-col :span="10">
                昵称：{{ wechatUserRecord.nickName }}
              </el-col>
            </el-row>
            <el-row class="item" :gutter="10">
              <el-col :span="14">
                性别：{{ wechatUserRecord.sex==1?"男":"女" }}
              </el-col>
              <el-col :span="10">
                语言：{{ wechatUserRecord.language }}
              </el-col>
            </el-row>

          </el-col>
          <el-col :span="4" class="tr">
            <img :src="wechatUserRecord.headImageUrl" class="common-round-image-96" data-default="avatar" @error="handleImageError">
          </el-col>
        </el-row>

        <el-row class="item" :gutter="10">
          <el-col :span="24">
            备注：{{ wechatUserRecord.remark }}
          </el-col>
        </el-row>
        <el-row class="item" :gutter="10">
          <el-col :span="12">
            地区：{{ wechatUserRecord.country }}-{{ wechatUserRecord.province }}-{{ wechatUserRecord.city }}
          </el-col>
          <el-col :span="12">
            分组：{{ wechatUserRecord.tagIdList }}
          </el-col>
        </el-row>
        <el-row class="item" :gutter="10">
          <el-col :span="8">
            订阅状态：
            <span v-if="wechatUserRecord.isCancle==0" class="color-primary">已关注</span>
            <span v-if="wechatUserRecord.isCancle==1" class="color-danger">已取消</span>
          </el-col>
          <el-col :span="8">
            订阅时间：{{ (wechatUserRecord.subscripeTime*1000 ) | formatDate }}
          </el-col>
          <el-col :span="8">
            取消时间：{{ (wechatUserRecord.unSubscripeTime*1000 ) | formatDate }}
          </el-col>
        </el-row>
        <el-row class="item" :gutter="10">
          <el-col :span="24">
            关注渠道：{{ subscribeScenes.filter((item)=>item.name===wechatUserRecord.subscribeScene)[0] }}
          </el-col>
        </el-row>
        <el-row class="item" :gutter="10">
          <el-col :span="12">
            二维码扫码场景：{{ wechatUserRecord.qrScene }}
          </el-col>
          <el-col :span="12">
            场景描述：{{ wechatUserRecord.rSceneStr }}
          </el-col>
        </el-row>

      </div>
    </model-dialog>
    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :model="wechatUserRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="AppId:" prop="appId">
            {{ wechatUserRecord.appId }}
          </el-form-item>
          <el-form-item label="用户标识:" prop="openId">
            {{ wechatUserRecord.openId }}
          </el-form-item>
          <el-form-item label="昵称:" prop="nickName">
            {{ wechatUserRecord.nickName }}
          </el-form-item>
          <el-form-item label="备注:" prop="remark">
            <el-input v-model="wechatUserRecord.remark" maxlength="30" show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item label="分组:" prop="tagIdList">
            <el-select v-model="wechatUserRecord.tagIdList" multiple placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in tagOptions"
                :key="item.id"
                :label="item.tagName"
                :value="item.tagId*1" />
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存 </el-button>
      </template>
    </side-box>

  </div>
</template>

<script>
import applicationKeySelect from '../applicationKeySelect'
export default {
  components: { applicationKeySelect },

  data() {
    return {
      total: 0,
      multipleSelectionRecords: [],
      list: [],
      listLoading: false,
      listQuery: {
        keyword: '',
        tagIdList: '',
        page: 1,
        appId: '',
        type: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        sort: this.common.SORT_DEFAULT
      },
      dialogVisible: false,
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create'
      },
      wechatUserRecord: {},
      tagOptions: [],
      subscribeScenes: [
        { name: 'ADD_SCENE_SEARCH', label: '公众号搜索' },
        { name: 'ADD_SCENE_ACCOUNT_MIGRATION', label: '公众号迁移' },
        { name: 'ADD_SCENE_PROFILE_CARD', label: '名片分享' },
        { name: 'ADD_SCENE_QR_CODE', label: '扫描二维码' },
        { name: 'ADD_SCENE_PROFILE_LINK', label: '图文页内名称点击' },
        { name: 'ADD_SCENE_PROFILE_ITEM', label: '图文页右上角菜单' },
        { name: 'ADD_SCENE_PAID', label: '支付后关注' },
        { name: 'ADD_SCENE_OTHERS', label: '其他' }
      ]

    }
  },
  watch: {
    'listQuery.tagIdList': function(val) {
      this.handleFilter()
    },
    'listQuery.appId': function(val) {
      this.handleFilter()
      this.fetchTags()
    }
  },
  created() {
  },
  methods: {
    // 表格自带方法开始
    /* 全选/反选*/
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /* 表格行数据单击*/
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /* 表格列排序*/
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    // 表格自带方法结束
    // 搜索
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    /**
     * 重置
     */
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        tagIdList: '',
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT
      }
      this.fetchData()
    },

    async handleSynchronizationUser() {
      try {
        this.listLoading = true
        await this.$store.dispatch('synchronizationWechatUser', this.listQuery.appId)
        this.$modal.msgSuccess('同步成功！')
        this.listLoading = false
        this.handleReset()
      } catch (_) {
        console.log()
      }
    },
    async fetchData() {
      const response = await this.$store.dispatch('wechatUserPage', this.listQuery)
      this.list = response.records
      this.total = response.total
    },
    /* 编辑*/
    handleUpdate(row) {
      this.wechatUserRecord = Object.assign({}, row) // copy obj
      this.wechatUserRecord = {
        ...this.wechatUserRecord,
        tagIdList: row.tagIdList ? JSON.parse(row.tagIdList) : []
      }
      console.log(this.wechatUserRecord)
      this.sideBox.status = 'update'
      this.sideBox.recordShow = true
      this.sideBox.title = '编辑微信用户'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.wechatUserRecord)
          if (this.wechatUserRecord.tagIdList) {
            delete tempData.tagIdList
            tempData.tagIdList = this.wechatUserRecord.tagIdList.join(',')
          }

          this.$store.dispatch('wechatUserUpdate', tempData).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    /* 删除*/
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('wechatUserRemove', ids).then(response => {
            this.handleReset()
            this.$modal.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.$modal.msgWarning('请选择要删除的记录')
      }
    },
    handleLook(row) {
      this.dialogVisible = true
      this.wechatUserRecord = row
    },
    fetchTags() {
      this.$store.dispatch('thirdWechatTagList', { appId: this.listQuery.appId }).then((res) => {
        this.tagOptions = res
      }).catch((_) => {})
    }

  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.wechatUserDetails{
    margin-top: 15px;
    .item{
      margin-bottom: 12px;
      font-size: 14px;
      font-weight: 500;
      color: #333;
    }
  }
</style>
